package com.shuimutong.paxos.demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shuimutong.paxos.demo.bean.bo.ProposalBo;
import com.shuimutong.paxos.demo.bean.dto.PrepareResDto;
import com.shuimutong.paxos.demo.service.AcceptorService;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicLong;

@Slf4j
public class Acceptor3ServiceImpl implements AcceptorService {
    private static AtomicLong maxNo = new AtomicLong(0);
    private static volatile String PROPOSAL_VAL;
    private final static Object LOCK = new Object();
    private final static Object LOCK1 = new Object();


    @Override
    public PrepareResDto prepare(ProposalBo proposal) {
        log.info("prepare,proposal:{}", JSONObject.toJSONString(proposal));
        if(maxNo.get() < proposal.getCode()) {
            synchronized (LOCK1) {
                if(maxNo.get() < proposal.getCode()) {
                    maxNo.set(proposal.getCode());
                    return new PrepareResDto(true, PROPOSAL_VAL);
                }
            }
        }
        return new PrepareResDto(false);
    }

    @Override
    public int accept(ProposalBo proposal) {
        log.info("accept,proposal:{}", JSONObject.toJSONString(proposal));
        int res = 0;
        if(maxNo.get() <= proposal.getCode()) {
            synchronized (LOCK) {
                if(maxNo.get() <= proposal.getCode()) {
                    PROPOSAL_VAL = proposal.getVal();
                    res = 1;
                }
            }
        }
        log.info("accept,proposal:{},res:{}", JSONObject.toJSONString(proposal), res);
        return res;
    }
}
